package com.enqualcomm.kids.activities;


import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.BuildConfig;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.base.MyHandler;
import com.enqualcomm.kids.base.MyResultReceiver;
import com.enqualcomm.kids.component.DownloadAppIntentService;
import com.enqualcomm.kids.component.InitContextIntentService;
import com.enqualcomm.kids.component.MyApplication;
import com.enqualcomm.kids.config.StateCode;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.GetNewAppParams;
import com.enqualcomm.kids.network.socket.response.GetNewAppResult;
import com.enqualcomm.kids.view.dialog.MyUpdateCommitDialog;
import com.iflytek.thridparty.G;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.Timer;
import java.util.TimerTask;

import common.utils.AnimationUtil;
import common.utils.BufferedSharedPreferences;
import common.utils.MyLogger;
import common.utils.PlatformUtil;

@EActivity(R.layout.new_splash_activity)
public class SplashActivity extends BaseActivity {
    private static final String GESTURE_CONFIG = "gesture_config";
    public static final String GESTURELOCK = "gesturelock";
    private static final int STAY_TIME_MILLIS = 1000;
    private static final int JUMP_TO_LOGIN = 1;
    private static final int TIME_LOCK = 2;
    private static final int GESTURE_LOCK = 3;
    private static final int TIMING = 4;
    private boolean timeLocked;
    private boolean dataLocked;
    private boolean hasNewApp;

    @ViewById(R.id.loading_iv)
    ImageView loading_iv;
    @ViewById(R.id.last_time_tv)
    TextView last_time_tv;
    @ViewById(R.id.bottom_tv)
    TextView bottom_tv;
    private NetworkModel networkModel;
    private boolean jumpToLogin;

    private int lastTime = 5;
    private boolean retBackFromGetData = false;

    private boolean deloyLoading = true;

    @AfterViews
    void show() {
        bottom_tv.setVisibility(deloyLoading ? View.VISIBLE : View.GONE);
        last_time_tv.setVisibility(deloyLoading ? View.VISIBLE : View.GONE);

//        SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
//        boolean showguide = sp.getBoolean("showguide", true);
//        if (showguide) {
            //新安装的用户
            newUser();
//        } else {
//            //兼容老用户
//            oldUser(sp);
//        }

        if ("喜书郎-喜书郎".equals(BuildConfig.CHANNEL) || "品冠达-平安星智能".equals(BuildConfig.CHANNEL)) {
            bottom_tv.setVisibility(View.GONE);
        }
    }

    private void oldUser(SharedPreferences sp) {
        sp.edit().remove("showguide").apply();
        sp.edit().putBoolean("old", true).apply();
        AppDefault appDefault = new AppDefault();
        appDefault.setGuidePicVersion(BuildConfig.GUIDE_VERSION);

        networkModel = new NetworkModel();
        checkForUpdate();

        loading_iv.setImageResource(R.drawable.loading);
        AnimationUtil.fadeIn(loading_iv);

        MyHandler handler = new MyHandler(this);
//        String username = sp.getString("username", null);
//        String password = sp.getString("password", null);
        String userid = appDefault.getUserid();
        if (userid != null) {//进行自动登陆操作
            timeLocked = true;
            dataLocked = true;
            if (deloyLoading) {
                showLastTime();
            } else {
                handler.sendEmptyMessageDelayed(TIME_LOCK, STAY_TIME_MILLIS);//用handler是为了保证在此页面停留1秒钟
            }

            loading(handler);
        } else { //没有保存登录状态，跳转登陆界面
            jumpToLogin = true;
            if (deloyLoading) {
                showLastTime();
            } else {
                handler.sendEmptyMessageDelayed(JUMP_TO_LOGIN, STAY_TIME_MILLIS);
            }

        }
    }

    private void newUser() {
        AppDefault appDefault = new AppDefault();
        if (appDefault.getGuidePicVersion() < BuildConfig.GUIDE_VERSION) {//有新的引导图片需要展示

            appDefault.setGuidePicVersion(BuildConfig.GUIDE_VERSION);
            startActivity(GuideActivity_.class);
            finish();
        } else {//不需要展示引导页
            //检查新版本
            networkModel = new NetworkModel();
            checkForUpdate();

            loading_iv.setImageResource(R.drawable.loading);
            AnimationUtil.fadeIn(loading_iv);

            MyHandler handler = new MyHandler(this);
            if (appDefault.getBbtreeUserid() != null) {//进行自动登陆操作
                timeLocked = true;
                dataLocked = true;
                if (deloyLoading) {
                    showLastTime();
                } else {
                    handler.sendEmptyMessageDelayed(TIME_LOCK, STAY_TIME_MILLIS);//用handler是为了保证在此页面停留1秒钟

                }
                loading(handler);
            } else { //没有保存登录状态，跳转登陆界面
                jumpToLogin = true;
                if (deloyLoading) {
                    showLastTime();
                } else {
                    handler.sendEmptyMessageDelayed(JUMP_TO_LOGIN, STAY_TIME_MILLIS);
                }
            }
        }
    }

    private void checkForUpdate() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            networkModel.loadDataFromServer(new SocketRequest<GetNewAppResult>(new GetNewAppParams(1, String.valueOf(BuildConfig.VERSION_CODE), BuildConfig.CHANNEL),
                    new NetworkListener<GetNewAppResult>() {
                        @Override
                        public void onError(VolleyError error) {
                        }

                        @Override
                        public void onSuccess(GetNewAppResult response) {
                            if (response.code == StateCode.OK && response.result.url != null) {
                                hasNewApp = true;
                                showCommitDialog(response);
                            }
                        }
                    }));
        }
    }

    private void showCommitDialog(final GetNewAppResult appInfo) {
        MyUpdateCommitDialog dialog = new MyUpdateCommitDialog(this, appInfo, new MyUpdateCommitDialog.UpdateCommitDialogCallBack() {

            @Override
            public void onCommit() {
                // 后台下载升级
                Intent service = new Intent(getApplicationContext(), DownloadAppIntentService.class);
                service.putExtra("url", appInfo.result.url);
                startService(service);
            }

            @Override
            public void onCancel() {
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface arg0) {
                hasNewApp = false;
                if (jumpToLogin) {
                    jumpToLoginAct();
                } else {
                    jumpToMainAct();
                }
            }
        });
        dialog.show();

    }

    @Override
    protected void handleMessage(Message msg) {
        switch (msg.what) {
            case JUMP_TO_LOGIN:
                jumpToLoginAct();
                break;
            case TIME_LOCK:
                timeLocked = false;
                jumpToMainAct();
//                showGestureLock();
                break;
            case TIMING:
                lastTime--;
                last_time_tv.setText(lastTime + "s");
                if (lastTime == 0 && retBackFromGetData) {  //从服务器获取数据成功，时间到了进行跳转
                    timeLocked = false;
                    jumpAction();
                } else if (lastTime <= 0 && jumpToLogin) { //服务器没有获取数据，但是需要跳转到登录界面
                    timeLocked = false;
                    jumpAction();
                } else if (lastTime <= 0) {   //服务器没有返回数据，时间已经到了停止时间等待从服务器返回数据
                    timeLocked = false;
                    last_time_tv.setVisibility(View.GONE);
                    timer.cancel();
                }
                break;
        }
    }


    private void showGestureLock() {
        BufferedSharedPreferences sp = MyApplication.getInstance().getSp(GESTURE_CONFIG);
        MyLogger.kLog().i("isOpenGestureLock:" + sp.getBoolean("isOpenGestureLock", false));
        if (sp.getBoolean("isOpenGestureLock", false)) {
            startActivity(GestureLockLoginActivity_.class);
            finish();
        } else {
            jumpToMainAct();

        }

    }


    @Override
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        dataLocked = false;

        if (deloyLoading) {
            retBackFromGetData = true;
            if (lastTime <= 0) {
                jumpAction();
            }
        } else {
            jumpToMainAct();
        }

//        if (resultCode == InitContextIntentService.SUCCESS) {
//            dataLocked = false;
//            jumpToMainAct();
//        } else {//PASSWORD_WRONG
//            //数据未取到，有可能是在其他地方修改了密码
////            jumpToLogin = true;
////            PromptUtil.toast(this, R.string.login_again);
////            jumpToLoginAct();
//
//            dataLocked = false;
//            jumpToMainAct();
//
//        }
    }

    private void loading(Handler handler) {
        Intent intent = new Intent(this, InitContextIntentService.class);
        intent.putExtra(InitContextIntentService.RECEIVER, new MyResultReceiver(handler, this));
        startService(intent);
    }

    private void jumpToMainAct() {
        if (!timeLocked && !dataLocked && !hasNewApp) {//如果数据取到了，停留时间也足够
            int windowWidth = PlatformUtil.windowWidth(this);
            int windowHeight = PlatformUtil.windowHeight(this);
            AppDefault appDefault = new AppDefault();
            appDefault.setWindowWidth(windowWidth);
            appDefault.setWindowHeight(windowHeight);
            startActivity(MainActivity_.class);
//
//            MyLogger.kLog().i("SplashActivity发送广播");
//            Intent intent = new Intent();
//            intent.setAction(GESTURELOCK);
//            sendBroadcast(intent);
            finish();
        }
    }

    private void jumpToLoginAct() {
        if (!hasNewApp) {
            startActivity(LoginActivity.class);
//            if ("品冠达-平安星智能".equals(BuildConfig.CHANNEL)) {
//                startActivity(LoginActivity.class);
//            } else {
//                startActivity(ChooseLoginActivity_.class);
//            }
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (networkModel != null) {
            networkModel.onStop();
        }
    }

    MyHandler handler = new MyHandler(this);
    Timer timer = new Timer("lastTime");

    void showLastTime() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(TIMING);
            }
        }, 0, 1000);
    }

    void jumpAction() {
        if (jumpToLogin) {
            jumpToLoginAct();
        } else {
            jumpToMainAct();
        }
    }


}
